package com.cms.framework;

import javax.servlet.http.*;

import com.cms.util.StringHelper;

import java.security.*;

public class CommandToken {
	public static void set(HttpServletRequest req) {
		HttpSession session = req.getSession(true);
		long system = System.currentTimeMillis();
		byte[] time = new Long(system).toString().getBytes();
		byte[] id = session.getId().getBytes();
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(time);
			md5.update(id);
			String token = toHex(md5.digest());
			req.setAttribute("token", token);
			session.setAttribute("token", token);
		} catch (Exception e) {
			System.err.println("Unable to calculate MD5 Digests");
		}
	}

	public static boolean isValid(HttpServletRequest req) {

		String requestToken = req.getParameter("token");
		return isValid(req.getSession(), requestToken);
	}

	public static boolean isValid(HttpSession session, String token) {
		String sessionToken = (String) session.getAttribute("token");
		if (StringHelper.isEmpty(token)) {
			return false;
		} else
			return token.equals(sessionToken);
	}

	private static String toHex(byte[] digest) {
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < digest.length; i++)
			buf.append(Integer.toHexString((int) digest[i] & 0x00ff));
		return buf.toString();
	}
}
